//
//  CreateTime.swift
//  时间的处理
//
//  Created by 陈锦彭 on 16/3/17.
//  Copyright © 2016年 chenjinpeng. All rights reserved.
//

import Foundation

extension NSDate {

    //"Thu Mar 17 20:02:48 +0800 2016"
    
    class func getCreatTime(creatAtString : String) -> String {
        //1.根据字符串转化成NSDate
        let dataFor = NSDateFormatter()
        dataFor.dateFormat = "EEE MM dd HH:mm:ss Z yyyy"
        dataFor.locale = NSLocale(localeIdentifier: "en")
        guard let createTime = dataFor.dateFromString(creatAtString) else {
        return ""
        }
        
        let nowDate = NSDate()
        //2.获取创建时间到现在的时间差
        let intervalTime = Int(nowDate.timeIntervalSinceDate(createTime))
        
        //3.判断是不是刚刚
        if intervalTime <= 60 {
        return  "刚刚"
        }

        //4.判断是不是一个小时前
        if intervalTime <= 60 * 60 {
        return  "\(intervalTime / 60)分钟前"
        }
        //创建日历对象
        let timeCalender = NSCalendar.currentCalendar()
        
        //5.判断是不是今天
        if timeCalender.isDateInToday(createTime) {
           dataFor.dateFormat = "HH:mm"
            let timeStr = dataFor.stringFromDate(createTime)
            return "今天\(timeStr)前"
        }
        
        //6.判断是不是昨天
        if timeCalender.isDateInYesterday(createTime) {
            dataFor.dateFormat = "HH:mm"
            let timeStr = dataFor.stringFromDate(createTime)
            return "昨天\(timeStr)前"
        }
        //7.判断是不是今年
        let com = timeCalender.components(.Year, fromDate: createTime, toDate: nowDate, options: [])
        if com.year < 1 {
         dataFor.dateFormat = "MM-dd HH:mm"
         let timeStr = dataFor.stringFromDate(createTime)
            return "\(timeStr)前"
        }
        //8.超过今年的
       
            dataFor.dateFormat = "yyyy-MM-dd HH:mm"
            let timeStr = dataFor.stringFromDate(createTime)
            return "\(timeStr)前"

    }
    
}
